package com.module.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.module.framework.domain.*;
import com.module.framework.dto.NowLendDTO;
import com.module.framework.mapper.*;
import com.module.framework.service.NowLendService;
import com.module.framework.vo.PageVO;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class NowLendServiceImpl extends ServiceImpl<NowLendMapper, NowLend> implements NowLendService {

    @Autowired
    private NowLendMapper nowLendMapper;

    @Autowired
    private HisLendMapper hisLendMapper;

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private UserMapper userMapper;

    @Resource
    private IndemnifyMapper indemnifyMapper;

    @Override
    public List<NowLend> findAllLend() {
        LambdaQueryWrapper<NowLend> queryWrapper = new LambdaQueryWrapper();
        List<NowLend> lists = list(queryWrapper);
        return lists;
    }

    @Override
    public PageVO nowLendList(NowLendDTO nowLendDTO) {
        Integer pageNum = nowLendDTO.getPageNum();
        Integer pageSize = nowLendDTO.getPageSize();
        String name = nowLendDTO.getName();
        String author = nowLendDTO.getAuthor();
        Integer cateId = nowLendDTO.getCateId();
        String userName = nowLendDTO.getUserName();
        Integer deadFlag = nowLendDTO.getDeadFlag();
        Integer status = nowLendDTO.getStatus();
        pageNum = (pageNum - 1) * pageSize;

        PageVO pageVO = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        Long roleId = loginUser.getUser().getRoleId();
        if (roleId != 3) {
            List<NowLend> lists = nowLendMapper.selectAllList(pageNum, pageSize, name, cateId, author, userName, deadFlag,status);
            pageVO = new PageVO(lists, lists.size());
        } else {
            // 当前用户
            List<NowLend> lists = nowLendMapper.selectByIdList(userId, pageNum, pageSize);
            pageVO = new PageVO(lists, lists.size());
        }
        return pageVO;
    }



    @Override
    public NowLend getNowLendInfo(Integer id) {
        NowLend nowLend = nowLendMapper.selectByIdVO(id);
        return nowLend;
    }

    @Override
    public String lendOutBook(Integer id) {
        NowLend nowLend = getById(id);
        if (nowLend.getDelayTime() == 0) {
            Date date = nowLend.getDeadline();

            Calendar c = Calendar.getInstance();
            c.setTime(date);
            c.add(Calendar.DAY_OF_MONTH, 30);
            SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String str2 = s.format(c.getTime());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime dateTime = LocalDateTime.parse(str2, formatter);
            long milleSecond = dateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();

            nowLend.setDeadline(new Date(milleSecond));
            nowLend.setDelayTime(1);
            nowLendMapper.updateById(nowLend);
            return "续借成功";
        } else {
            return "您已经续借一次了，不能再次续借！";
        }
    }

    @Override
    public String lendBackBook(Integer id) {
        NowLend nowLend = getById(id);
        Long userId = nowLend.getUserId();
        Integer bookId = nowLend.getBookId();

        // 历史记录插入一条
        HisLend hisLend = new HisLend();
        hisLend.setBookId(bookId);
        hisLend.setDeadline(nowLend.getDeadline());
        hisLend.setType(0);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        hisLend.setReturnTime(date);
        hisLend.setUserId(userId);
        hisLendMapper.insert(hisLend);

        // 剩余书本+1
        Book book = bookMapper.selectById(bookId);
        book.setSpareNumber(book.getSpareNumber() + 1);
        bookMapper.updateById(book);

        // 用户借书-1
        User user = userMapper.selectById(userId);
        user.setLendNumber(user.getLendNumber() - 1);
        userMapper.updateById(user);

        // 删除
        nowLendMapper.deleteById(id);

        return "归还成功";
    }

    @Override
    public String lendBackBook2(Integer id) {
        NowLend nowLend = getById(id);
        Long userId = nowLend.getUserId();
        Integer bookId = nowLend.getBookId();

        // 历史记录插入一条
        HisLend hisLend = new HisLend();
        hisLend.setBookId(bookId);
        hisLend.setDeadline(nowLend.getDeadline());
        hisLend.setType(1);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        hisLend.setReturnTime(date);
        hisLend.setUserId(userId);
        hisLendMapper.insert(hisLend);

        // 剩余书本+1
        Book book = bookMapper.selectById(bookId);
        book.setSpareNumber(book.getSpareNumber() + 1);
        bookMapper.updateById(book);

        // 用户借书-1
        User user = userMapper.selectById(userId);
        user.setLendNumber(user.getLendNumber() - 1);
        user.setBan(user.getBan() - 1);
        userMapper.updateById(user);

        // 删除
        nowLendMapper.deleteById(id);

        //逾期归还新增赔付记录
        Indemnify indemnify = new Indemnify();
        indemnify.setBookId(bookId);
        indemnify.setUserId(userId);
        //计算赔付金额，逾期一天一块钱
        indemnify.setCompensationAmount(String.valueOf((int) ((date.getTime() - nowLend.getDeadline().getTime()) / (1000 * 60 * 60 * 24))));
        indemnify.setCompensationReason("逾期"+ (int) ((date.getTime() - nowLend.getDeadline().getTime()) / (1000 * 60 * 60 * 24)) + "天");
        indemnify.setCompensationStatus("1");
        indemnifyMapper.insert(indemnify);

        return "归还成功";
    }

    @Override
    public String lendLoss(Integer id) {
        NowLend nowLend = getById(id);
        Long userId = nowLend.getUserId();
        Integer bookId = nowLend.getBookId();
        nowLend.setStatus(1);
        nowLend.setLossTime(new Date());
        nowLendMapper.updateById(nowLend);
        //挂失新增赔付记录
        Indemnify indemnify = new Indemnify();
        indemnify.setBookId(bookId);
        indemnify.setUserId(userId);
        //按照书籍原价赔付
        Book book = bookMapper.selectById(bookId);
        indemnify.setCompensationAmount(String.valueOf(book.getPrice()));
        indemnify.setCompensationReason("书籍遗失");
        indemnify.setCompensationStatus("1");
        indemnifyMapper.insert(indemnify);
        return "挂失成功";
    }


}
